package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.R;
import com.example.reggie.entity.Category;
import com.example.reggie.entity.Dish;
import com.example.reggie.entity.DishDto;
import com.example.reggie.entity.DishFlavor;
import com.example.reggie.service.impl.CategoryServiceImpl;
import com.example.reggie.service.impl.DishFlavorServiceImpl;
import com.example.reggie.service.impl.DishServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishServiceImpl dishService;

    @Autowired
    private DishFlavorServiceImpl dishFlavorService;

    @Autowired
    private CategoryServiceImpl categoryService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /*分页查询和条件查询*/
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){



        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Dish::getName,name);

        /*排序*/
        wrapper.orderByDesc(Dish::getUpdateTime);
        /**/
        IPage<Dish> iPage = dishService.page(new Page<>(page, pageSize),wrapper);
        /*获取总条数*/
        long total = iPage.getTotal();
        /*获取数据*/
        List<Dish> records = iPage.getRecords();

        Map map = new HashMap();
        map.put("total", total);

        ArrayList<DishDto> list = new ArrayList<>();
        for (Dish dish : records) {
            /*获取id为了让菜和对应分类做比较*/
            Long categoryId = dish.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            /*获取菜名*/
            String byIdName = byId.getName();
            DishDto dishDto = new DishDto();
            /*放入菜的类型*/
            dishDto.setCategoryName(byIdName);

            /*将共有的属性放入dishDto中*/
            BeanUtils.copyProperties(dish,dishDto);
            list.add(dishDto);
        }
        map.put("records",list);

        /*因为前端读取了俩个东西所以需要传map集合*/
        return R.success(map);
    }


    /*新增*/
    @PostMapping
    public R add(@RequestBody DishDto dishDto){
        dishService.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors!=null&&flavors.size()>0){
            /*获取id是为了保持一致*/
            Long id = dishDto.getId();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
                dishFlavorService.save(flavor);
            }
        }
        /*新增完之后为了保证数据redis与mysql数据库保持一致那么就需要去清除掉redis中的数据,也可以换成其他方法*/
        redisTemplate.delete("dish_"+dishDto.getCategoryId());
        return R.success("添加成功");
    }

    /*修改(回显数据)*/
    @GetMapping("/{id}")
    public R huixian(@PathVariable Long id){
        /*根据id查询Dish数据*/
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getId,id);
        /*查询口味*/
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);

        /*获取通过模糊查询得到的值*/
        Dish dish = dishService.getOne(wrapper);

        /*为了修改之后保持一致*/
        redisTemplate.delete("dish_"+dish.getCategoryId());

        List<DishFlavor> dishFlavor = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

        DishDto dishDto = new DishDto();
        /*将查询的值放入Dto*/
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavor);

        return R.success(dishDto);
    }

    /*真修改*/
    @PutMapping
    public R up(@RequestBody DishDto dishDto){
        dishService.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(wrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
            dishFlavorService.save(flavor);
        }
        /*为了保证修改之后的数据保持一致*/
        redisTemplate.delete("dish_"+dishDto.getCategoryId());
        return R.success("修改成功");
    }


    /*数组和集合必须要加上@RequestParam这个注解*/
    @DeleteMapping
    public R deleted(@RequestParam ArrayList<Long> ids){
        /*为了修改之后保持一致*/
        for (Long id : ids) {
            Dish byId = dishService.getById(id);
            redisTemplate.delete("dish_"+byId.getCategoryId());
        }
        /*删除菜品*/
        dishService.removeByIds(ids);
        /*删除口味*/
        dishFlavorService.removeByIds(ids);

        return R.success("删除成功");
    }
    /*起售/停售 批量起售/批量停售*/
    @PostMapping("/status/{status}")
    public R status(@RequestParam ArrayList<Long> ids,@PathVariable Integer status){

        for (Long id : ids) {
            Dish newDish = new Dish();
            newDish.setId(id);
            newDish.setStatus(status);

            dishService.updateById(newDish);

            /*为了修改之后保持一致*/
            Dish byId = dishService.getById(id);
            redisTemplate.delete("dish_"+byId.getCategoryId());
        }
        return R.success("修改成功");
    }

    /*根据分类id查询该分类下的所有菜品集合 */
    @GetMapping("/list")
    /*菜品分类id和起售停售0是停1是起*/
    public R list(Long categoryId,Long status){

        /*先判断Redis中有没有数据,由于名字需要为string类型的所以通过字符串的拼接来转换为string类型*/
        ArrayList<DishDto> dtoList = (ArrayList<DishDto>) redisTemplate.opsForValue().get("dish_"+categoryId);

        if (dtoList!=null){
            return R.success(dtoList);
        }

        /*没有数据情况下就去数据库中取*/
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        wrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(wrapper);

        ArrayList<DishDto> dishDtos = new ArrayList<>();

        for (Dish dish : list) {
//遍历 List<Dish> 集合，获取每一个Dish对象，转变成DishDto对象，放入到新的集合 List<DishDto>
            DishDto dishDto = new DishDto();

            /*添加*/
            BeanUtils.copyProperties(dish,dishDto);

            /*添加口味*/
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            dishDtos.add(dishDto);
            /*放入redis中*/
            redisTemplate.opsForValue().set("dish_"+categoryId,dishDtos);
        }

        return R.success(dishDtos);
    }
}
